# -*- coding:utf-8 -*-
import os, sys
from datetime import datetime, timedelta
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
import supeanut_config
from DataAPI.DatayesAPI import DatayesAPI
from CommonLib.db.MongoDBTool import MongoDBTool
from CommonLib.FileTool.CsvTool import CsvTool
from CommonLib.mylog import mylog


'''
作者：supeanut
创建时间：2016-12-12 22:16
功能描述：
	股市基本信息获取，存到本地csv或线上mongo（若可用）
	基本信息包括：个股上退市，停复牌，交易日历
相关配置：
	supeanut_config.Local Data
历史改动：
	2016-12-13 支持stockinfo和calendar的本地存储，mongo暂不支持
'''
class BasicDataSupport:
	def __init__(self):
		self.datayes_obj = DatayesAPI()
		self.csv_obj = CsvTool()
		self.stockinfo_field = supeanut_config.STOCKINFO_DATAYES_FIELD
		self.stockinfo_index = supeanut_config.STOCKINFO_DATAYES_INDEX
		self.stockinfo_csvpath = supeanut_config.STOCKINFO_CSV_PATH
		self.stockinfo_csvname = supeanut_config.STOCKINFO_CSV_FILE
		self.dateinfo_field = supeanut_config.CALENDAR_DATAYES_FIELD
		self.dateinfo_index = supeanut_config.CALENDAR_DATAYES_INDEX
		self.dateinfo_csvpath = supeanut_config.CALENDAR_CSV_PATH
		self.dateinfo_csvname = supeanut_config.CALENDAR_CSV_FILE


	def stock_info_support(self, method = 'csv'):
		log = mylog('DataSupport.BasicDataSupport.stock_info_support', None)
		flag, data = self.datayes_obj.stock_info()
		if flag is False:
			return False, data
		if method == 'csv':
			# 按照配置信息的字段顺序组合数据
			record_list = []
			for stock_code in data:
				onestock_info_list = [stock_code]
				stock_info_dict = data[stock_code]
				# [:1]与supeanut_config.STOCKINFO_DATAYES_INDEX/FIELD以及DATAYES接口共同决定
				for field in self.stockinfo_field[1:]:
					onestock_info_list.append(stock_info_dict[field])
				record_list.append(onestock_info_list)
			flag, msg = self.csv_obj.new_csvfile(record_list, self.stockinfo_csvpath, self.stockinfo_csvname)
			if flag is False and msg == 'file already exists':
				upd_flag, upd_msg = self.csv_obj.update_csvfile(self.stockinfo_index, record_list, self.stockinfo_csvpath, self.stockinfo_csvname)
			elif flag is False:
				return False, msg
			else:
				return True, 'suc'
			return upd_flag, upd_msg
		elif method == 'mongo':
			mongodb_obj = MongoDBTool(None, config.MONGO_DB, config.MONGO_COLL_STOCKINFO)
			flag, msg = mongodb_obj.conn()
			if flag is False:
				return False, msg
			update_suc_tag = True
			for stock_code in data:
				stock_info = data[stock_code]
				flag, msg = mongodb_obj.update({'stock_code': stock_code},
											   {'$set': {'intomarket_date': stock_info['intomarket_date'],
														 'total_shares': stock_info['total_shares'],
														 'outmarket_date': stock_info['outmarket_date'],
														 'status': stock_info['status'],
														 'board': stock_info['board'],
														 'short_name': stock_info['short_name'],
														 'circulate_shares': stock_info['circulate_shares'],
														 'full_name': stock_info['full_name']}},
											   True, True)
				if flag is False:
					update_suc_tag = False
					continue
			if update_suc_tag is False:
				return False, 'update failed, see mongo log file'
			log.info('suc')
			return True, 'suc'
		else:
			return False, 'support method should be in (csv, mongo)'

	def stock_suspension_support(self):
		# 待实现
		today = datetime.today()
		today_str = today.strftime('%Y-%m-%d')
		mongodb_obj = MongoDBTool(None, config.MONGO_DB, config.MONGO_COLL_SUSPENSION, "../Log/MongoDB.log")
		flag, msg = mongodb_obj.conn()
		if flag is False:
			return False, msg
		flag, data = self.datayes_obj.stock_suspension()
		if flag is False:
			return False, data
		update_suc_tag = True
		for status in data:
			flag, msg = mongodb_obj.update({'date': today_str, 'status': status}, {'$set': {'code_list': data[status]}},
										   True, True)
			if flag is False:
				update_suc_tag = False
		if update_suc_tag is False:
			return False, 'update mongo failed, see mongo log file'
		return True, 'suc'

	def trade_calendar_support(self, method='csv'):
		log = mylog('DataSupport.BasicDataSupport.trade_calendar_support', None)
		flag, data = self.datayes_obj.trade_calendar()
		if flag is False:
			return False, data
		if method == 'csv':
			# 按照配置信息的字段顺序组合数据
			record_list = []
			for date in data:
				onedate_info_list = [date]
				date_info_dict = data[date]
				# [:1]与supeanut_config.CALENDAR_DATAYES_INDEX/FIELD以及DATAYES接口共同决定
				for field in self.dateinfo_field[1:]:
					onedate_info_list.append(date_info_dict[field])
				record_list.append(onedate_info_list)
			flag, msg = self.csv_obj.new_csvfile(record_list, self.dateinfo_csvpath, self.dateinfo_csvname)
			if flag is False and msg == 'file already exists':
				upd_flag, upd_msg = self.csv_obj.update_csvfile(self.dateinfo_index, record_list, self.dateinfo_csvpath, self.dateinfo_csvname)
			elif flag is False:
				return False, msg
			else:
				return True, 'suc'
			return upd_flag, upd_msg
		elif method == 'mongo':
			mongodb_obj = MongoDBTool(None, config.MONGO_DB, config.MONGO_COLL_TRADE_CALENDAR)
			flag, msg = mongodb_obj.conn()
			if flag is False:
				return False, msg
			update_suc_tag = True
			for date in data:
				date_info = data[date]
				flag, msg = mongodb_obj.update({'date': date}, {'$set': {'isOpen': date_info['isOpen'],
																		 'prevTradeDate': date_info['prevTradeDate'],
																		 'exchangeCD': date_info['exchangeCD']}},
											   True, True)
				if flag is False:
					update_suc_tag = False
			if update_suc_tag is False:
				return False, 'update mongo failed, see mongo log file'
			log.info('suc')
			return True, 'suc'
		else:
			return False, 'support method should be in (csv, mongo)'

if __name__ == '__main__':
	obj = BasicDataSupport()
	# 每日更新？
	print(obj.stock_info_support(method='csv'))
	# 每日更新？
	#print(obj.stock_suspension_support(method='csv'))
	# 每日更新？
	print(obj.trade_calendar_support(method='csv'))
